package com.cool.orchestration.client;

import com.cool.common.exception.BusinessException;
import com.cool.orchestration.auth.TokenProvider;
import com.cool.orchestration.exception.ApiExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.Map;

public class ThirdPartyApiClient {
    private final OkHttpClient okHttpClient;
    private final ObjectMapper objectMapper;
    private final TokenProvider tokenProvider;
    private final ApiExceptionHandler exceptionHandler;

    @Value("${thirdparty.api.base-url}")
    private String baseUrl;

    public ThirdPartyApiClient(OkHttpClient okHttpClient,
                               ObjectMapper objectMapper,
                               TokenProvider tokenProvider,
                               ApiExceptionHandler exceptionHandler) {
        this.okHttpClient = okHttpClient;
        this.objectMapper = objectMapper;
        this.tokenProvider = tokenProvider;
        this.exceptionHandler = exceptionHandler;
    }

    // 通用GET请求方法
    public <T> T get(String path, Map<String, Object> params, Class<T> responseType) {
        String url = buildUrl(path, params);
        Request request = buildRequest(url, null, HttpMethod.GET);

        try (Response response = okHttpClient.newCall(request).execute()) {
            return processResponse(response, responseType);
        } catch (IOException e) {
            throw exceptionHandler.handleException(e);
        }
    }

    // 通用POST请求方法
    public <T, R> T post(String path, R requestBody, Class<T> responseType) {
        String url = baseUrl + path;
        RequestBody body = buildRequestBody(requestBody);
        Request request = buildRequest(url, body, HttpMethod.POST);

        try (Response response = okHttpClient.newCall(request).execute()) {
            return processResponse(response, responseType);
        } catch (IOException e) {
            throw exceptionHandler.handleException(e);
        }
    }

    // 构建带参数的URL
    private String buildUrl(String path, Map<String, Object> params) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl + path).newBuilder();
        if (params != null) {
            // params.forEach(urlBuilder::addQueryParameter);
            params.forEach((key, value) -> urlBuilder.addQueryParameter(key, value.toString()));
        }
        return urlBuilder.build().toString();
    }

    // 构建HTTP请求
    private Request buildRequest(String url, RequestBody body, HttpMethod method) {
        Request.Builder builder = new Request.Builder()
                .url(url)
                .headers(createHeaders());

        switch (method) {
            case GET:
                builder.get();
                break;
            case POST:
                builder.post(body);
                break;
            case PUT:
                builder.put(body);
                break;
            case DELETE:
                builder.delete(body);
                break;
        }

        return builder.build();
    }

    // 构建请求体
    private RequestBody buildRequestBody(Object requestBody) {
        if (requestBody == null) {
            return RequestBody.create(null, new byte[0]);
        }

        try {
            String json = objectMapper.writeValueAsString(requestBody);
            return RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        } catch (Exception e) {
            throw new BusinessException("5000", "请求体序列化失败: " + e.getMessage());
        }
    }

    // 创建HTTP请求头
    private Headers createHeaders() {
        return new Headers.Builder()
                .add("Accept", "application/json")
                .add("Authorization", "Bearer " + tokenProvider.getAccessToken())
                .build();
    }

    // 处理响应
    private <T> T processResponse(Response response, Class<T> responseType) throws IOException {
        if (response.isSuccessful()) {
            if (response.body() == null) {
                return null;
            }
            return objectMapper.readValue(response.body().string(), responseType);
        } else {
            String errorMessage = response.body() != null ? response.body().string() : "未知错误";
            throw new BusinessException("5001",
                    "第三方API调用失败(" + response.code() + "): " + errorMessage);
        }
    }

    private enum HttpMethod {
        GET, POST, PUT, DELETE
    }
}